/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package multiface.promonet.servlet.section.action;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import multiface.promonet.jpa.File;
import multiface.promonet.jpa.Utente;
import multiface.promonet.jpa.util.PersistenceManager;
import multiface.web.util.Define;

/**
 *
 * @author Diego64
 */
public class ActionFile {

    public static void delFile(HttpServletRequest request, HttpServletResponse response) {
        HttpSession s = request.getSession();
        if (s.getAttribute(Define.USER_SESSION) != null) {
            Utente u_session = (Utente) s.getAttribute(Define.USER_SESSION);

            EntityManagerFactory emf = PersistenceManager.getInstance().getEntityManagerFactory();
            EntityManager em = emf.createEntityManager();



            File c = em.find(File.class, Integer.parseInt(request.getParameter("fid")));
            em.getTransaction().begin();
            em.remove(c);
            em.getTransaction().commit();

            em.close();
        }
    }

    public static void setCoverFile(HttpServletRequest request, HttpServletResponse response) {
        HttpSession s = request.getSession();
        if (s.getAttribute(Define.USER_SESSION) != null) {
            Utente u_session = (Utente) s.getAttribute(Define.USER_SESSION);

            EntityManagerFactory emf = PersistenceManager.getInstance().getEntityManagerFactory();
            EntityManager em = emf.createEntityManager();

            Utente u = em.find(Utente.class, u_session.getIdutente());
            em.refresh(u);
            List<File> lf = u.getFileList();

            em.getTransaction().begin();
            for (File f : lf) {
                f.setCopertina(false);
                if (f.getIdfile() == Integer.parseInt(request.getParameter("fid"))) {
                    f.setCopertina(true);
                }
                em.persist(f);
            }
            em.getTransaction().commit();

            em.close();
        }
    }
}
